package cn.yunyichina.provider.merchant.task;

import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.merchant.constant.RedisKey;
import cn.yunyichina.provider.merchant.task.execute.MerchantNotifyMessageExecute;
import cn.yunyichina.utils.log.Log;
import cn.yunyichina.utils.log.constant.LogScene;

import java.util.Calendar;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by kevin on 2017/12/7.
 */
public class MerchantNotifyMessageTask {
    private final AtomicLong idGen = new AtomicLong();

    //KEY的超时时间，该时间一定要比定时器轮询的时间长
    private final static int KEY_EXPIRE_TIME=60*2;

    //是否拿到执行的权限
    private  boolean isGetAccessToken=false;

    public void startUp() {
        boolean isGetKey=false;
        if(!isGetAccessToken){
            isGetKey= CacheService.getCacheClient().getLock(RedisKey.MERCHANT_NOTIFY_MESSAGE_TASK_KEY,KEY_EXPIRE_TIME);
        }
        Log.i(LogScene.MERCHANT_MESSAGE_NOTIFY,"isGetKey:"+isGetKey+",isGetAccessToken:"+isGetAccessToken);
        if(isGetKey||isGetAccessToken){
            isGetAccessToken=true;
            long count = idGen.incrementAndGet();
            Log.i(LogScene.MERCHANT_MESSAGE_NOTIFY,"第 " + count + " 商户消息通知作业开始....................");
            Long statrTime = Calendar.getInstance().getTimeInMillis();

            MerchantNotifyMessageExecute execute=new MerchantNotifyMessageExecute();
            execute.start();

            Long endTime = Calendar.getInstance().getTimeInMillis();
            CacheService.getCacheClient().expireKey(RedisKey.MERCHANT_NOTIFY_MESSAGE_TASK_KEY,KEY_EXPIRE_TIME);
            Log.i(LogScene.MERCHANT_MESSAGE_NOTIFY,"第 " + count + " 次商户消息通知结束 ,耗费时间:" + ( endTime - statrTime ) + " Millis");
        }
    }
}
